package user_dal

import (
	"gorm.io/gorm"
	"starry_sky/internal/dal"
	"starry_sky/internal/model"
)

// FindUserByUserName 根据用户名查找用户，适用：bcrypt
func FindUserByUserName(userName string) (model.User, error) {
	var user model.User
	err := dal.DB.Where("username = ?", userName).First(&user).Error
	if err != nil {
		return model.User{}, err
	}
	return user, err
}

// ClearUserAndRole 清除用户与角色关系
func ClearUserAndRole(db *gorm.DB, user *model.User) error {
	err := db.Model(&user).Association("Roles").Clear()
	if err != nil {
		return err
	}
	return nil
}

// BindUserAndRole 绑定用户与角色关系
func BindUserAndRole(db *gorm.DB, user *model.User, roles []model.Role) error {
	err := db.Model(&user).Association("Roles").Append(roles)
	if err != nil {
		return err
	}
	return nil
}
